package com.nomi.blog.controller;

import com.alibaba.fastjson.JSONObject;
import com.nomi.blog.entity.User;
import com.nomi.blog.service.UserService;
import com.nomi.blog.utils.Result;
import com.nomi.blog.utils.FileUploadUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

//    @Autowired
//    private FileUploadUtils fileUploadUtils;

    /**
     * 用户注册
     * @param user
     * @return
     */
    @PostMapping("/register")
    public Result register(@RequestBody User user) {
        return userService.register(user);
    }

    /**
     * 用户登录
     * @param user
     * @return
     */
    @PostMapping("/login")
    public Result login(@RequestBody User user) {
        System.out.println(user);
        String identifier = user.getAccount() != null ? user.getAccount() : user.getNickname();
        String password = user.getPassword();
        return userService.login(identifier,password);
    }

    /**
     * 发送重置密码验证码
     * @param jsonObject
     * @return
     */
    @PostMapping("/sendVerificationCode")
    public Result sendVerificationCode(@RequestBody JSONObject jsonObject) {
        System.out.println(jsonObject);
        String email = jsonObject.getString("email");
        System.out.println(email);
        return userService.sendVerificationCode(email);
    }

    /**
     * 重置密码
     * @param jsonObject
     * @return
     */
    @PostMapping("/resetPassword")
    public Result resetPassword(@RequestBody JSONObject jsonObject){
        String email = jsonObject.getString("email");
        String code = jsonObject.getString("code");
        String newPassword = jsonObject.getString("newPassword");
        return userService.resetPassword(email, code, newPassword);
    }

    /**
     * 获取当前用户信息
     * @return
     */
    @GetMapping("/info")
    public Result getUserInfo() {
        return userService.getCurrentUserInfo();
    }

    /**
     * 通过用户Id获取当前用户信息
     */
    @GetMapping("/info/{userId}")
    public Result getUserInfo(@PathVariable Long userId) {
        return userService.getUserInfo(userId);
    }

    /**
     * 更新用户信息
     * @param user
     * @return
     */
    @PutMapping("/info")
    public Result updateUserInfo(@RequestBody User user){
        return userService.updateUserInfo(user);
    }

    /**
     * 上传头像
     * @param file
     * @return
     * @throws IOException
     */
    @PostMapping("/upload")
    public Result uploadAvatar(@RequestParam("file") MultipartFile file) throws IOException {
        return userService.uploadAvatar(file);
    }

}
